import { App, Plugin, PluginSettingTab, Setting, Notice } from "obsidian";
import * as CryptoJS from "crypto-js";
import "./styles.css"; 

interface PasswordProtectionSettings {
	passwordHash: string;
	isEnabled: boolean;
}

const DEFAULT_SETTINGS: PasswordProtectionSettings = {
	passwordHash: "",
	isEnabled: false,
};

class PasswordPrompt {
	private app: App;
	private settings: PasswordProtectionSettings;
	private onSuccess: () => void;

	constructor(
		app: App,
		settings: PasswordProtectionSettings,
		onSuccess: () => void
	) {
		this.app = app;
		this.settings = settings;
		this.onSuccess = onSuccess;
		this.createPrompt();
	}

	createPrompt() {
		const overlay = document.createElement("div");
		overlay.className = "password-protection-overlay";

		const container = document.createElement("div");
		container.className = "password-protection-container";

		const title = document.createElement("div");
		title.textContent = "笔记启动验证";
		title.className = "password-protection-title";

		const passwordInput = document.createElement("input");
		passwordInput.type = "password";
		passwordInput.placeholder = "输入密码";
		passwordInput.className = "password-protection-input";

		const msg = document.createElement("div");
		msg.textContent = "请输入笔记启动的密码！";
		msg.className = "password-protection-msg";

		const confirmBtn = document.createElement("button");
		confirmBtn.textContent = "确认";
		confirmBtn.className = "password-protection-confirm-btn";

		container.appendChild(title);
		container.appendChild(passwordInput);
		container.appendChild(msg);
		container.appendChild(confirmBtn);
		overlay.appendChild(container);
		document.body.appendChild(overlay);


		passwordInput.addEventListener("keydown", (e) => {
			if (e.key === "Enter") {
				this.verifyPassword(passwordInput.value, overlay, msg);
			}
		});
		passwordInput.addEventListener("blur", () => {
			if (passwordInput.value == "" || passwordInput.value.length == 0) {
				msg.textContent = "请输入笔记启动的密码！";
				msg.className = "password-protection-msg";
			}
		});

		confirmBtn.addEventListener("click", () =>
			this.verifyPassword(passwordInput.value, overlay, msg)
		);
	}

	private verifyPassword(
		input: string,
		overlay: HTMLElement,
		msg: HTMLElement
	) {
		if (input == "" || input.length == 0) {
			msg.textContent = "请输入密码！";
			msg.className = "password-protection-warning-msg";
			return;
		}

		const hash = CryptoJS.SHA256(input).toString();
		if (hash === this.settings.passwordHash) {
			overlay.remove();
			this.onSuccess();
		} else {
			msg.textContent = "密码错误，请重试！";
			msg.className = "password-protection-warning-msg";
		}
	}
}

export default class PasswordProtectionPlugin extends Plugin {
	settings: PasswordProtectionSettings;

	async onload() {
		await this.loadSettings();
		this.addSettingTab(new PasswordProtectionSettingTab(this.app, this));
		if (this.settings.isEnabled && this.settings.passwordHash) {
			this.showPasswordPrompt();
		}
	}

	private showPasswordPrompt() {
		new PasswordPrompt(this.app, this.settings, () => {
			new Notice("解锁成功！");
		});
	}

	async saveSettings() {
		await this.saveData(this.settings);
	}

	async loadSettings() {
		this.settings = { ...DEFAULT_SETTINGS, ...(await this.loadData()) };
	}
}

class PasswordProtectionSettingTab extends PluginSettingTab {
	plugin: PasswordProtectionPlugin;

	constructor(app: App, plugin: PasswordProtectionPlugin) {
		super(app, plugin);
		this.plugin = plugin;
	}

	display(): void {
		const { containerEl } = this;

		containerEl.empty();
		containerEl.createEl("h2", { text: "密码保护设置" });

		new Setting(containerEl)
			.setName("启用密码保护")
			.setDesc("每次打开Obsidian时需要输入密码")
			.addToggle((toggle) =>
				toggle
					.setValue(this.plugin.settings.isEnabled)
					.onChange(async (value) => {
						this.plugin.settings.isEnabled = value;
						await this.plugin.saveSettings();
					})
			);

		new Setting(containerEl)
			.setName("设置密码")
			.setDesc("请设置密码以保护你的笔记")
			.addText((text) => {
				text.inputEl.type = "password";
				text.setPlaceholder("输入新密码");
				text.inputEl.className = "setting-password-protection-input";
				text.inputEl.addEventListener("blur", async () => {
					const value = text.getValue();
					if (value) {
						this.plugin.settings.passwordHash =
							CryptoJS.SHA256(value).toString();
						await this.plugin.saveSettings();
						new Notice("密码设置成功");
					}
				});
			});
	}
}
